import {useMutation} from "@tanstack/react-query";
import {create} from "zustand";
import {createJSONStorage, persist} from "zustand/middleware";
import userService, {type SignInReq} from "@/api/services/userService";
import {toast} from "sonner";
import type {UserInfo, UserToken} from "#/entity";
import {StorageEnum} from "#/enum";

type UserStore = {
    userInfo: Partial<UserInfo>;
    userToken: UserToken;

    actions: {
        setUserInfo: (userInfo: UserInfo) => void;
        setUserToken: (token: UserToken) => void;
        clearUserInfoAndToken: () => void;
    };
};

const useUserStore = create<UserStore>()(
    persist(
        (set) => ({
            userInfo: {},
            userToken: {},
            actions: {
                setUserInfo: (userInfo) => {
                    set({userInfo});
                },
                setUserToken: (userToken) => {
                    set({userToken});
                },
                clearUserInfoAndToken() {
                    set({userInfo: {}, userToken: {}});
                },
            },
        }),
        {
            name: "userStore", // name of the item in the storage (must be unique)
            storage: createJSONStorage(() => localStorage), // (optional) by default, 'localStorage' is used
            partialize: (state) => ({
                [StorageEnum.UserInfo]: state.userInfo,
                [StorageEnum.UserToken]: state.userToken,
            }),
        },
    ),
);

export const useUserInfo = () => useUserStore((state) => state.userInfo);
export const useUserToken = () => useUserStore((state) => state.userToken);
export const useUserActions = () => useUserStore((state) => state.actions);

export const useSignIn = () => {
    const {setUserToken, setUserInfo} = useUserActions();

    const signInMutation = useMutation({
        mutationFn: userService.signIn,
    });

    return async (data: SignInReq) => {
        try {
            const res = await signInMutation.mutateAsync(data);
            const {token, user_name, phone_number} = res;
            setUserToken({token});
            setUserInfo({user_name, phone_number});
        } catch (err) {
            toast.error(err.message, {
                position: "top-center",
            });
            throw err;
        }
    };
};

export default useUserStore;
